import { BlogInfo } from '@/api/blog/types';
import { associateBlogWithCollection as associateBlogWithCollectionAPI } from '@/api/collection';
import { BLOG_STATUS } from '@/constants/common/blog-status';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

/**
 * 博客编辑器状态管理Store
 * @description 用于管理博客创作相关的状态，包括编辑器状态、自动保存、写作统计等
 * @author 系统
 * @version 2.0.0
 * @since 2024-01-01
 */
export const useBlogStore = defineStore(
  'blogState',
  () => {
    // 基础博客信息
    const blogInfo = ref<BlogInfo>({
      blogId: '',
      blogTitle: '',
      blogContent: '',
      blogContentType: 'markdown',
      blogCategoryId: '',
      blogTags: [],
      blogCoverImage: '',
      blogSubUrl: '',
      enableComment: true,
      blogStatus: BLOG_STATUS.DRAFT,
      importance: false,
      collectionId: undefined
    });

    // 编辑器状态
    const editorState = ref({
      isFullscreen: false,
      isFocusMode: false,
      sidebarCollapsed: false,
      activeEditor: 'rich' as 'markdown' | 'rich', // 默认使用富文本编辑器
      autoSave: true,
      wordCount: 0,
      lastSaved: null as Date | null,
      autoSaveInterval: 30000, // 30秒自动保存
      isLoading: false,
      hasUnsavedChanges: false
    });

    // 写作统计
    const writingStats = computed(() => {
      const content = blogInfo.value.blogContent || '';
      return {
        wordCount: content.length,
        charCount: content.replace(/\s/g, '').length,
        readingTime: Math.ceil(content.length / 500), // 假设每分钟阅读500字
        paragraphCount: content.split('\n\n').filter(p => p.trim()).length
      };
    });

    // 注意：移除了重复的localBackup机制，统一使用Pinia持久化

    // 保存初始状态用于比较
    const initialBlogState = ref<BlogInfo>({ ...blogInfo.value });

    // 深度比较两个对象是否相等
    const isDeepEqual = (obj1: any, obj2: any): boolean =>
      JSON.stringify(obj1) === JSON.stringify(obj2);

    // 检查是否有实质性变化
    const checkForChanges = (oldData: BlogInfo, newData: Partial<BlogInfo>): boolean => {
      // 只比较传入的字段是否有变化
      const hasChanges =
        (newData.blogTitle !== undefined && oldData.blogTitle !== newData.blogTitle) ||
        (newData.blogContent !== undefined && oldData.blogContent !== newData.blogContent) ||
        (newData.blogCategoryId !== undefined &&
          oldData.blogCategoryId !== newData.blogCategoryId) ||
        (newData.blogTags !== undefined &&
          JSON.stringify(oldData.blogTags || []) !== JSON.stringify(newData.blogTags || [])) ||
        (newData.blogCoverImage !== undefined &&
          oldData.blogCoverImage !== newData.blogCoverImage) ||
        (newData.enableComment !== undefined && oldData.enableComment !== newData.enableComment) ||
        (newData.importance !== undefined && oldData.importance !== newData.importance);

      return hasChanges;
    };

    // 检查内容是否与上次保存时不同
    const hasChangedFromLastSave = (): boolean => {
      const current = blogInfo.value;
      const saved = savedBlogState.value;

      return (
        current.blogTitle !== saved.blogTitle ||
        current.blogContent !== saved.blogContent ||
        current.blogCategoryId !== saved.blogCategoryId ||
        JSON.stringify(current.blogTags || []) !== JSON.stringify(saved.blogTags || []) ||
        current.blogCoverImage !== saved.blogCoverImage ||
        current.enableComment !== saved.enableComment ||
        current.importance !== saved.importance
      );
    };

    // 智能检测是否需要自动保存
    const needsAutoSave = (): boolean => {
      if (!editorState.value.hasUnsavedChanges) return false;
      if (!editorState.value.autoSave) return false;

      // 检查是否有实际内容
      const hasContent =
        blogInfo.value.blogTitle.trim() !== '' ||
        blogInfo.value.blogContent.trim() !== '' ||
        blogInfo.value.blogCategoryId !== '' ||
        (blogInfo.value.blogTags && blogInfo.value.blogTags.length > 0) ||
        blogInfo.value.blogCoverImage.trim() !== '';

      return hasContent && hasChangedFromLastSave();
    };

    // 设置博客信息
    const setBlogInfo = (blog: Partial<BlogInfo>, isInitialLoad = false) => {
      const oldBlogInfo = { ...blogInfo.value };

      // 如果是初始加载（从服务器加载文章数据），不标记为未保存
      if (isInitialLoad) {
        blogInfo.value = {
          ...blogInfo.value,
          ...blog
        };
        // 加载完成后，更新保存状态快照并标记为已保存
        editorState.value.hasUnsavedChanges = false;
        savedBlogState.value = { ...blogInfo.value };
        return Promise.resolve(null);
      }

      // 先检查是否有实质性变化（使用更新前的值）
      const hasChanges = checkForChanges(oldBlogInfo, blog);

      blogInfo.value = {
        ...blogInfo.value,
        ...blog
      };

      // 只有在检测到实质性变化时才标记为未保存
      if (hasChanges) {
        editorState.value.hasUnsavedChanges = true;
      }

      return Promise.resolve(null);
    };

    // 更新编辑器状态
    const updateEditorState = (state: Partial<typeof editorState.value>) => {
      editorState.value = {
        ...editorState.value,
        ...state
      };
      return Promise.resolve(null);
    };

    // 更新内容
    const updateContent = (
      content: string,
      contentType?: 'markdown' | 'rich',
      isInitialLoad = false
    ) => {
      // 检查内容是否真的发生了变化
      const contentChanged = blogInfo.value.blogContent !== content;
      const typeChanged = contentType && blogInfo.value.blogContentType !== contentType;

      if (contentChanged || typeChanged) {
        setBlogInfo(
          {
            blogContent: content,
            blogContentType: contentType || blogInfo.value.blogContentType
          },
          isInitialLoad
        );
        // 只有当内容真正变化时才标记为未保存
        // setBlogInfo函数内部会通过checkForChangesWithOldData来判断是否设置hasUnsavedChanges
      }
    };

    // 保存到本地备份（使用统一的缓存键名）
    const saveLocalBackup = () => {
      localStorage.setItem('blogLocalBackup', JSON.stringify(blogInfo.value));
    };

    // 清除本地备份
    const clearLocalBackup = () => {
      localStorage.removeItem('blogLocalBackup');
    };

    // 重置博客状态
    const resetBlogState = () => {
      blogInfo.value = {
        blogId: '',
        blogTitle: '',
        blogContent: '',
        blogContentType: 'rich', // 默认富文本
        blogCategoryId: '',
        blogTags: [],
        blogCoverImage: '',
        blogSubUrl: '',
        enableComment: true,
        blogStatus: BLOG_STATUS.DRAFT,
        importance: false,
        collectionId: undefined
      };
      editorState.value = {
        isFullscreen: false,
        isFocusMode: false,
        sidebarCollapsed: false,
        activeEditor: 'rich', // 默认富文本编辑器
        autoSave: true,
        wordCount: 0,
        lastSaved: null,
        autoSaveInterval: 30000,
        isLoading: false,
        hasUnsavedChanges: false
      };
      clearLocalBackup();
      // 清空保存状态快照
      savedBlogState.value = { ...blogInfo.value };
      return Promise.resolve(null);
    };

    // 检查本地备份是否有实质性内容
    const hasMeaningfulContent = (backup: any): boolean => {
      if (!backup) return false;

      // 检查是否有实质性内容（排除默认值）
      const hasTitle =
        backup.blogTitle &&
        backup.blogTitle.trim() !== '' &&
        !backup.blogTitle.includes('未命名文章');

      const hasContent =
        backup.blogContent &&
        backup.blogContent.trim() !== '' &&
        backup.blogContent !== '<p>在这里写下你的内容...</p>' &&
        backup.blogContent !== '在这里写下你的内容...';

      const hasCategory = backup.blogCategoryId && backup.blogCategoryId.trim() !== '';

      const hasTags = backup.blogTags && backup.blogTags.length > 0;

      const hasCoverImage =
        backup.blogCoverImage &&
        backup.blogCoverImage.trim() !== '' &&
        backup.blogCoverImage !== '/static/img/default.jpeg';

      // 只要有以上任何一项内容，就认为是有意义的
      return hasTitle || hasContent || hasCategory || hasTags || hasCoverImage;
    };

    // 检查是否应该清理缓存（当没有未保存内容时）
    const shouldClearCache = (): boolean => {
      // 如果当前没有未保存的更改，应该清理缓存
      if (!editorState.value.hasUnsavedChanges) {
        return true;
      }

      // 如果当前内容没有实质性内容（只有默认值），也应该清理缓存
      const backup = localStorage.getItem('blogLocalBackup');
      if (backup && !hasMeaningfulContent(JSON.parse(backup))) {
        return true;
      }

      // 如果当前内容与上次保存时完全相同，也应该清理缓存
      if (!hasChangedFromLastSave()) {
        return true;
      }

      return false;
    };

    // 在页面离开时清理缓存
    const clearCacheOnPageLeave = () => {
      const shouldClear = shouldClearCache();
      console.log('页面离开时缓存清理检查:', {
        hasUnsavedChanges: editorState.value.hasUnsavedChanges,
        shouldClear,
        hasBackup: !!localStorage.getItem('blogLocalBackup')
      });

      if (shouldClear) {
        // 只清理临时缓存，不重置blogInfo
        // 重置逻辑移到页面进入时处理，避免误触发内容变化
        clearLocalBackup();
      }
    };

    // 智能初始化文章：根据缓存内容决定是否恢复
    const smartInitializeArticle = async () => {
      const backup = localStorage.getItem('blogLocalBackup');

      if (backup) {
        try {
          const parsedBackup = JSON.parse(backup);

          // 检查是否有实质性内容
          if (hasMeaningfulContent(parsedBackup)) {
            // 有实质性内容，恢复缓存但不标记为未保存状态
            // 用户可能只是想查看，不应该立即标记为未保存
            await setBlogInfo(parsedBackup, true); // 使用isInitialLoad=true，避免标记为未保存
            // 不设置 hasUnsavedChanges = true，让用户自然编辑时才标记
            return Promise.resolve(true); // 表示恢复了缓存
          } else {
            // 没有实质性内容，清空缓存但不创建新文章
            clearLocalBackup();
            await resetBlogState();
            return Promise.resolve(false);
          }
        } catch (error) {
          console.error('解析本地备份失败:', error);
          // 解析失败，清空缓存但不创建新文章
          clearLocalBackup();
          await resetBlogState();
          return Promise.resolve(false);
        }
      } else {
        // 没有备份，重置状态但不创建新文章模板
        await resetBlogState();
        return Promise.resolve(false);
      }
    };

    // 初始化新文章的默认值
    const initializeNewArticle = () => {
      const now = new Date();
      const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
        2,
        '0'
      )}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(
        2,
        '0'
      )}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

      // 设置默认文章信息
      blogInfo.value = {
        blogId: '',
        blogTitle: `未命名文章 ${timestamp}`,
        blogContent: '<p>在这里写下你的内容...</p>',
        blogContentType: 'rich', // 默认富文本
        blogCategoryId: '', // 将由 getCategoryOptions 方法设置
        blogTags: [],
        blogCoverImage: '/static/img/default.jpeg', // 默认封面图片
        blogSubUrl: '',
        enableComment: true,
        blogStatus: BLOG_STATUS.DRAFT,
        importance: false, // 默认不置顶
        collectionId: undefined
      };

      // 重置编辑器状态
      editorState.value = {
        isFullscreen: false,
        isFocusMode: false,
        sidebarCollapsed: false,
        activeEditor: 'rich', // 默认富文本编辑器
        autoSave: true,
        wordCount: 0,
        lastSaved: null,
        autoSaveInterval: 30000,
        isLoading: false,
        hasUnsavedChanges: false // 新文章默认没有未保存的更改
      };

      // 清除本地备份和保存状态
      clearLocalBackup();
      savedBlogState.value = { ...blogInfo.value };

      return Promise.resolve(null);
    };

    // 检查是否为新建文章
    const isNewArticle = (): boolean => !blogInfo.value.blogId || blogInfo.value.blogId === '';

    // 保存时的状态快照
    const savedBlogState = ref<BlogInfo>({ ...blogInfo.value });

    // 标记为已保存
    const markAsSaved = () => {
      // 首先清理缓存，防止后续操作重新创建
      clearLocalBackup();

      // 设置保存状态
      editorState.value.hasUnsavedChanges = false;
      editorState.value.lastSaved = new Date();

      // 更新保存时的状态快照
      savedBlogState.value = { ...blogInfo.value };
    };

    // 关联文章到合集
    const associateBlogToCollection = async (blogId: string, collectionId: string) => {
      try {
        const response = await associateBlogWithCollectionAPI({
          blogId,
          collectionId
        });
        return response.data;
      } catch (error) {
        console.error('关联文章到合集失败:', error);
        throw error;
      }
    };

    // 确保lastSaved是Date对象（修复从localStorage恢复后的类型问题）
    const ensureLastSavedIsDate = () => {
      if (editorState.value.lastSaved && !(editorState.value.lastSaved instanceof Date)) {
        // 如果是字符串，尝试转换为Date对象
        const parsedDate = new Date(editorState.value.lastSaved as any);
        if (!isNaN(parsedDate.getTime())) {
          editorState.value.lastSaved = parsedDate;
        } else {
          // 如果转换失败，设置为null
          editorState.value.lastSaved = null;
        }
      }
    };

    // 在store初始化时修复lastSaved类型
    ensureLastSavedIsDate();

    return {
      // 状态
      blogInfo,
      editorState,
      writingStats,

      // 方法
      setBlogInfo,
      updateEditorState,
      updateContent,
      saveLocalBackup,
      clearLocalBackup,
      resetBlogState,
      initializeNewArticle,
      smartInitializeArticle,
      isNewArticle,
      markAsSaved,
      needsAutoSave,
      hasChangedFromLastSave,
      ensureLastSavedIsDate,
      hasMeaningfulContent,
      shouldClearCache,
      clearCacheOnPageLeave,
      associateBlogToCollection
    };
  },
  {
    // 持久化存储配置
    persist: {
      key: 'blogState',
      storage: window.localStorage,
      pick: ['blogInfo', 'editorState'] // 只持久化这些字段
    }
  }
);
